package com.hspedu.event_;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;

public class BallMove extends JFrame{
    MyPanel mp = null;
    public static void main(String[] args) {
        BallMove ballMove = new BallMove();
    }

    public BallMove() {
        mp = new MyPanel();
        this.add(mp);
        this.setSize(400, 300);
        this.addKeyListener(mp); //监听键盘事件
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}

//实现键盘监听器
class MyPanel extends JPanel implements KeyListener {
    //小球移动，小球的坐标设置为变量
    int x = 10;
    int y = 10;

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x, y, 20, 20);

    }

    //有字符输出
    @Override
    public void keyTyped(KeyEvent e) {

    }

    //当某个键按下
    @Override
    public void keyPressed(KeyEvent e) {
        //上下左右控制小球
        if(e.getKeyCode() == KeyEvent.VK_DOWN){
            y++;
        } else if(e.getKeyCode() == KeyEvent.VK_UP){
            y--;
        } else if(e.getKeyCode() == KeyEvent.VK_LEFT){
            x--;
        } else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
            x++;
        }
        this.repaint(); //面板重绘
    }

    //当某个键释放
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
